﻿/*
 * This file is part of MonoSettlers.
 *
 * Copyright (C) 2010-2011 Christoph Husse
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: 
 *      # Christoph Husse
 * 
 * Also checkout our homepage: http://opensettlers.codeplex.com/
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

#if EMBEDDED
    using OpenTK.Graphics.ES20;
#else
using OpenTK.Graphics.OpenGL;
#endif

namespace MonoSettlers.RenderSystem
{
    /// <summary>
    /// Extends the base renderable with functionality to render an
    /// <see cref="Animation"/>. The next level is <see cref="RenderableAnimationSet"/>,
    /// followed by the topmost level <see cref="RenderableAnimationClass"/>.
    /// </summary>
    /// <remarks>
    /// With OpenGL always keep in mind that the we have to call ALL GL commands
    /// withtin the same thread, usually the internal render loop thread. So any
    /// methods and properties exposed to the public MUSTN'T call any GL commands,
    /// instead the calls shall be deferred.
    /// </remarks>
    public class RenderableAnimation : RenderableVisual
    {
        private static List<NativeTexture> m_FrameCache = new List<NativeTexture>();
        private Animation m_Animation;

        /// <summary>
        /// Gets or sets the animation rendered by this visual. If you set a new one,
        /// <see cref="FrameIndex"/> is reset to zero.
        /// </summary>
        public Animation Animation
        {
            get { return m_Animation; }
            set
            {
                m_Animation = value;

                if (value != null)
                {
                    AspectRatio = value.Width / (double)value.Height;
                }

                SetFrameIndex(0);
            }
        }
        /// <summary>
        /// Gets the animation frame currently being displayed.
        /// </summary>
        public AnimationFrame Frame { get; private set; }
        /// <summary>
        /// Gets the index of the animation frame currently being displayed.
        /// </summary>
        public Int32 FrameIndex { get; private set; }
        /// <summary>
        /// Is animation playing (true) or suspended?
        /// </summary>
        public bool IsPlaying { get; set; }

        /// <summary>
        /// Initialization without an initial animation (can be set later).
        /// </summary>
        public RenderableAnimation(GLRenderer inParent) : this(inParent, null)
        {
        }

        /// <summary>
        /// Initialization with an initial animation.
        /// </summary>
        public RenderableAnimation(GLRenderer inParent, Animation inAnimation) : base(inParent)
        {
            Animation = inAnimation;
        }

        /// <summary>
        /// Setting a frame is almost as fast as a variable assignment.
        /// Just the first time a frame is set, it needs to be loaded and
        /// cached.
        /// </summary>
        public void SetFrameIndex(Int32 inFrameIndex)
        {
            if (Animation == null)
            {
                Frame = null;
                Texture = null;

                return;
            }

            AnimationFrame frame = Animation.Frames.ElementAt(inFrameIndex);

            while (frame.Index >= m_FrameCache.Count)
            {
                m_FrameCache.Add(null);
            }

            Frame = frame;
            FrameIndex = inFrameIndex;

            // actually loading the frame must be deferred until rendering, due to wrong thread context.
        }

        /// <summary>
        /// This method is ONLY called from the rendering thread. It's safe to call OpenGL methods
        /// but make it quick, since this method gets called three times per frame ;). Pay attention
        /// to thread-safety since most members are subject to be changed by other threads simultaneously.
        /// </summary>
        internal override void Render()
        {
            // Load current frame... ("Frame" is NOT thread-safe, intentionally internalizing member to prevent wrong usage.)
            var Frame = this.Frame;
            var Animation = this.Animation;

            if (Frame == null)
                return;

            var entry = m_FrameCache[Frame.Index];

            if (entry == null)
            {
                entry = m_FrameCache[Frame.Index] = new NativeTexture(Parent, Frame.Source);
            }

            Texture = entry;

            int offsetX = Animation.OffsetX + Frame.OffsetX;
            int offsetY = Animation.OffsetY + Frame.OffsetY;

            Render(
                Animation.OffsetX * Parent.Scale,
                Animation.OffsetY * Parent.Scale,
                Frame.Width * Parent.Scale,
                Frame.Height * Parent.Scale);
        }
    }
}
